/**
 * 许可证相关中间件
 *
 * Created by snowingsea on 2020/02/24.
 */
const license = require('./../../models/license');
const PhoenixError = require('./../../models/phoenix-error');
const { checkExpiration } = require('../../helpers/licenseHelper');

/**
 * 需要当前许可证存在
 * @param req
 * @param res
 * @param next
 */
function requireLicenseExist(req, res, next) {
  license.getLicense()
    .then((res) => {
      if (!res) {
        return Promise.reject(new PhoenixError('not found', 'Not found, license not found'));
      }
      req.$license = res;
      return Promise.resolve();
    })
    .then(() => {
      next();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 防止用户通过修改系统时间，绕开许可证过期检测。如果系统时间正常，改接口会更新记录文件的时间戳。
 */
function detectSystemTimeTampering(_req, _res, next) {
  return (
    checkExpiration()
      .then((isValid) => {
        if (!isValid) {
          return Promise.reject(new PhoenixError('systemtime error', 'There are some problems about your license, please contact the vendor.'));
        }
        return Promise.resolve();
      })
      .then(next)
      .catch((err) => {
        next(new PhoenixError(err));
      })
  );
}

/**
 * Export model definition object.
 */
module.exports = {
  requireLicenseExist,
  detectSystemTimeTampering,
};
